package com.mbs.framework.shiro.service;

import com.mbs.project.system.user.domain.UserRole;
import com.mbs.project.system.user.mapper.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.mbs.common.constant.Constants;
import com.mbs.common.constant.ShiroConstants;
import com.mbs.common.constant.UserConstants;
import com.mbs.common.utils.DateUtils;
import com.mbs.common.utils.MessageUtils;
import com.mbs.common.utils.ServletUtils;
import com.mbs.framework.manager.AsyncManager;
import com.mbs.framework.manager.factory.AsyncFactory;
import com.mbs.project.system.user.domain.User;
import com.mbs.project.system.user.service.IUserService;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 注册校验方法
 *
 * @author xyl
 */
@Component
public class RegisterService {
    @Autowired
    private IUserService userService;
    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 注册
     */
    public String register(User user) {
        String msg = "", loginName = user.getLoginName(), password = user.getPassword(), email = user.getEmail();
        if (!StringUtils.isEmpty(ServletUtils.getRequest().getAttribute(ShiroConstants.CURRENT_CAPTCHA))) {
            msg = "验证码错误";
        } else if (StringUtils.isEmpty(loginName)) {
            msg = "用户名不能为空";
        } else if (StringUtils.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if(StringUtils.isEmpty(email)){
            msg = "邮件不能为空";
        } else if(!Pattern.matches(UserConstants.EMAIL_PATTERN, email)){
            msg = "邮件格式有误";
        }else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在5到20个字符之间";
        } else if (loginName.length() < UserConstants.USERNAME_MIN_LENGTH
                || loginName.length() > UserConstants.USERNAME_MAX_LENGTH) {
            msg = "账户长度必须在2到20个字符之间";
        } else if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(loginName))) {
            msg = "保存用户'" + loginName + "'失败，注册账号已存在";
        } else if(UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkEmailUnique(user))){
            msg = "保存用户'" + email + "'失败，邮箱已存在";
        }else {
            user.setPwdUpdateDate(DateUtils.getNowDate());
            user.setUserName(loginName);
            user.setRoleId(3L);
            user.setEmail(email);
            boolean regFlag = userService.registerUser(user);
            insertUserRole(user.getUserId(), user.getRoleId());
            if (!regFlag) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.REGISTER, MessageUtils.message("user.register.success")));
            }
        }
        return msg;
    }

    /**
     * 新增用户角色信息
     */
    private void insertUserRole(Long userId, Long roleId) {
        List<UserRole> roles = new ArrayList<>();
        UserRole ur = new UserRole();
        ur.setUserId(userId);
        ur.setRoleId(roleId);
        roles.add(ur);
        userRoleMapper.batchUserRole(roles);
    }
}
